
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

def func(x, p): # 函数形式
    A,k,theta = p
    return A*np.sin(2*np.pi*k*x+theta)

def residual(p,y,x): # 误差函数
    return y - func(x,p)

A,k,theta = 10, 0.34, np.pi/6
x = np.linspace(-2*np.pi, 0, 100)
y1 = func(x, [A,k,theta]) + 2 * np.random.randn(len(x))
plsq = leastsq(residual, [7,0.2,0], args=(y1,x))
plt.plot(x,y1,'o',x,func(x,plsq[0]),'--')
plt.savefig("../../../doc/marp-slides/leastsq.png")
plt.show()
print(u"真实参数：", [A,k,theta])
print(u"拟合参数：", plsq[0])

